package cn.edu.zafu.bigdata.XuShuXin.Exp1119;
import java.io.*;
import java.util.*;
/**
 * @author: aluvfy
 * @description:
 * @date: 2024/11/19 11:10
 */
public class StudentManager_xsx {
    private static final String FILE_PATH = "students.dat";
    private List<Student> students = new ArrayList<>();

    public StudentManager_xsx() {
        loadStudents();
    }

    private void loadStudents() {
        File file = new File(FILE_PATH);
        if (!file.exists() || file.length() == 0) {
            return; // 文件不存在或为空时，跳过加载
        }

        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(FILE_PATH))) {
            students = (List<Student>) ois.readObject();
        } catch (FileNotFoundException e) {
            // 文件不存在时，首次运行时忽略
        } catch (EOFException e) {
            // 遇到EOF异常时，表示文件内容可能不完整或损坏
            System.err.println("文件读取错误，可能文件已损坏：" + e.getMessage());
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void saveStudents() {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(FILE_PATH))) {
            oos.writeObject(students);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void addStudent(String id, String name, String phone) {
        for (Student student : students) {
            if (student.getId().equals(id)) {
                System.out.println("学号重复，请重新输入。");
                return;
            }
        }
        students.add(new Student(id, name, phone));
        saveStudents();
        System.out.println("学生信息已保存。");
    }

    public void searchStudent(String id) {
        for (Student student : students) {
            if (student.getId().equals(id)) {
                System.out.println(student);
                return;
            }
        }
        System.out.println("未找到该学生");
    }

    public void updateStudent(String id, String name, String phone) {
        for (Student student : students) {
            if (student.getId().equals(id)) {
                student.setName(name);
                student.setPhone(phone);
                saveStudents();
                System.out.println("学生信息已更新。");
                return;
            }
        }
        System.out.println("未找到该学生");
    }

    public void deleteStudent(String id) {
        Iterator<Student> iterator = students.iterator();
        while (iterator.hasNext()) {
            Student student = iterator.next();
            if (student.getId().equals(id)) {
                iterator.remove();
                saveStudents();
                System.out.println("学生信息已删除。");
                return;
            }
        }
        System.out.println("未找到该学生");
    }
}